package com.yj.change.db;

import android.content.Context;
import android.content.SharedPreferences;

import com.yj.change.Config;

import java.util.HashSet;
import java.util.Set;

import de.robv.android.xposed.XSharedPreferences;

public class HookDB {

    private static HookDB hookDB;
    private Set<String> hookApps;
    private boolean isXShare = false;

    public static HookDB getIntance(Context context) {
        if (hookDB == null) {
            synchronized (HookDB.class) {
                if (hookDB == null) {
                    if (context == null) {
                        hookDB = new HookDB();
                    } else {
                        hookDB = new HookDB(context);
                    }
                }
            }
        } else {
            hookDB.reload();
        }
        return hookDB;
    }

    public static HookDB getIntance() {
        return getIntance(null);
    }

    private void reload() {
        if (isXShare) {
            ((XSharedPreferences) sharedPreferences).reload();
        }
    }

    private SharedPreferences sharedPreferences;

    private HookDB(Context context) {
        isXShare = false;
        sharedPreferences = context.getSharedPreferences("hookDB", 0);
    }

    private HookDB() {
        isXShare = true;
        XSharedPreferences xSharedPreferences = new XSharedPreferences(Config.packageName, "hookDB");
        xSharedPreferences.makeWorldReadable();
        this.sharedPreferences = xSharedPreferences;
    }

    public Set<String> readHookApps() {
        if (isXShare) {
            reload();
            return sharedPreferences.getStringSet("apps", new HashSet<String>());
        }
        if (hookApps == null) {
            hookApps = sharedPreferences.getStringSet("apps", new HashSet<String>());
        }
        return hookApps;
    }

    public void saveHook() {
        sharedPreferences.edit().putStringSet("apps", hookApps).apply();
    }


}
